package com.cat.dataStructure02;

import java.util.PriorityQueue;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-number-of-eaten-apples/
 * @create 2025/10/27 11:58
 * @since JDK17
 */

public class Solution70 {
    public int eatenApples(int[] apples, int[] days) {
        int n = apples.length, ans = 0;
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        for (int i = 0; i < n || !heap.isEmpty(); i++) {
            while (!heap.isEmpty() && heap.peek()[0] == i) {  // 弹出腐烂的苹果
                heap.poll();
            }
            if (i < n && apples[i] > 0) {    // 有苹果
                heap.add(new int[]{i + days[i], apples[i]});
            }
            if (!heap.isEmpty()) {
                ans++;
                if (--heap.peek()[1] == 0) {    // 吃完了也得弹出
                    heap.poll();
                }
            }
        }

        return ans;
    }
}
